package com.xiaozhen.sso.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaozhen.sso.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ： 甄维胜
 * @createTime ：2021/10/2 15:25
 * HISTORY :
 */
@Api(tags = "码云登录接口")
@RestController
@RequestMapping("/gitee")
public class GiteeController {

    @Value("${redirect.gateway.path}")
    private String gatewayPath;
    @Value("${redirect.page.path}")
    private String pagePath;

    @Autowired
    private LoginService loginService;

    @ApiOperation("码云登录接口")
    @GetMapping("/login")
    public void login(AuthCallback authCallback, HttpServletResponse response) throws IOException {
        // 创建授权request
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId("7267c575584f46166aa3baa6c58acee5346f3f31bc1756579ca902a8165481b4")
                .clientSecret("d042ffae26b222373421dcf56c2a87ae0cfadee6a9d6e0aa698978b5c55ff8a7")
                .redirectUri(gatewayPath + "/xiaozhen-sso/gitee/login")
                .ignoreCheckState(true)
                .build());
        // 授权登录后会返回code（auth_code（仅限支付宝））、state，1.8.0版本后，可以用AuthCallback类作为回调接口的参数
        // 注：JustAuth默认保存state的时效为3分钟，3分钟内未使用则会自动清除过期的state
        AuthResponse login = authRequest.login(authCallback);
        //处理登录信息  关联到平台用户
        Long userId = loginService.handle(login);
        //这里先写死
        userId = 1L;
        if (userId != null) {
            if (!StpUtil.isLogin()) {
                StpUtil.login(userId);
            }
            response.sendRedirect(pagePath + "/login/" + StpUtil.getTokenValue());
        } else {
            //跳转到绑定页面

        }
    }
}
